package com.ophiux.appoint.proxy;

import com.ophiux.appoint.service.MyService;
import com.ophiux.appoint.service.impl.MyServiceImpl;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @desc: JDK反射机制生成代理
 * @author: hhl
 * @date：2023/10/7 11:36
 */
public class MyProxy {

    //维护一个目标对象
    private Object target;

    //对象构造时，提供目标对象
    public MyProxy(Object target) {
        this.target = target;
    }

    //给目标对象生成代理对象
    public Object getProxyInstance() {
        return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("日志打印： before");
                //执行目标对象方法
                Object returnValue = method.invoke(target, args);
                System.out.println("日志打印： after");
                return returnValue;
            }
        });
    }

    public static void main(String[] args) {
        MyService myService = new MyServiceImpl();
        MyService myProxy = (MyService) new MyProxy(myService).getProxyInstance();
        myProxy.eat();
        myProxy.sleep();
    }

}